package com.hzeport.bgs22emduty.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenNoticeDTO;
import com.hzeport.bgs22emduty.dto.messgeDistribute.ScreenMessageDistributeHideDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.NoticeEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.outbound.BaseDeptInfoRepository;
import com.hzeport.bgs22emduty.outbound.ScreenNoticeRepository;
import com.hzeport.bgs22emduty.vo.ParamDuty.ParamDutyListVO;
import com.hzeport.bgs22emduty.vo.ScreenNotice.ScreenNoticeListVO;
import com.hzeport.bgs22emduty.vo.ScreenNotice.ScreenNoticeSaveVO;
import com.hzeport.bgs22emduty.vo.ScreenNotice.postarticlesVO;
import com.hzeport.bgs22emduty.vo.ScreenStandard.ScreenStandardsaveVO;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.outbound.db.ScreenNoticeRepositoryImpl;
import com.hzeport.bgs22emduty.service.ScreenNoticeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.swing.*;
import java.awt.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenNoticeServiceImpl extends BaseServiceImpl<ScreenNoticeRepositoryImpl, ScreenNotice> implements ScreenNoticeService {

    @Resource
    private ScreenNoticeRepository screenNoticeRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private AppendixRepository appendixRepository;

    @Override
    public BaseResult<Page<ScreenNoticeListVO>> list(ScreenNoticeDTO dto, UserInfoDetailVO userInfoDetailVO) {
        Page<ScreenNotice> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        LambdaQueryWrapper<ScreenNotice> queryWrapper=new LambdaQueryWrapper<>();
        if(!CollectionUtils.isEmpty(dto.getData())&&dto.getData().get(0)!=null){
            queryWrapper.ge(ScreenNotice::getApplyTime, LocalDateTime.parse(dto.getData().get(0)+"T00:00:00"));
        }
        if(!CollectionUtils.isEmpty(dto.getData())&&dto.getData().get(1)!=null){
            queryWrapper.le(ScreenNotice::getApplyTime, LocalDateTime.parse(dto.getData().get(1)+"T23:59:59"));
        }
        if(!StringUtils.isEmpty(dto.getTitle())){
            queryWrapper.like(ScreenNotice::getTitle,dto.getTitle());
        }
        queryWrapper.orderByDesc(ScreenNotice::getSort);
        queryWrapper.orderByDesc( BaseEntity::getCreateTime );


        Page<ScreenNotice> standardPage = screenNoticeRepository.page(page, queryWrapper);
        List<ScreenNoticeListVO> screenNoticeListVOS=new ArrayList<>();
        for (ScreenNotice screenNotice : standardPage.getRecords()) {
            ScreenNoticeListVO screenNoticeListVO = new ScreenNoticeListVO();
            BeanUtils.copyProperties(screenNotice,screenNoticeListVO);
            screenNoticeListVOS.add(screenNoticeListVO);
        }
        Page<ScreenNoticeListVO> listVOPage = new Page<>();
        listVOPage.setRecords(screenNoticeListVOS);
        listVOPage.setTotal(page.getTotal());

        return BaseResult.ok(listVOPage,"查询成功");
    }

    @Override
    public BaseResult delete(String id, UserInfoDetailVO userInfoDetailVO) {
        screenNoticeRepository.update(new LambdaUpdateWrapper<ScreenNotice>()
                .eq(ScreenNotice::getId,id)
                .set(ScreenNotice::getDelFlag, DeleteFlagEnum.IS_DELETE.getValue())
                .set(ScreenNotice::getUpdateBy,userInfoDetailVO.getUserId())
                .set(ScreenNotice::getUpdateTime, LocalDateTime.now()));
        appendixRepository.remove(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,id));
        return BaseResult.ok(null,"删除成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult save(ScreenNoticeSaveVO screenNoticeSaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        Calendar instance = Calendar.getInstance();
        int year=instance.get(Calendar.YEAR);
        ScreenNotice screenNotice = new ScreenNotice();
        BeanUtils.copyProperties(screenNoticeSaveVO,screenNotice);
//        if ()
//        screenNotice.setJumpUrl(systemConfig.getMyPdfUrl()+file.getCurrentFileName());
        //查出今年的发文倒序取第一个
        List<ScreenNotice> noticeList=screenNoticeRepository.list(new LambdaQueryWrapper<ScreenNotice>()
                .eq(ScreenNotice::getYear,year).eq(ScreenNotice::getStatus,"0").orderByDesc(ScreenNotice::getSort));
        if(StringUtils.isEmpty(screenNoticeSaveVO.getId())){
            if(CollectionUtils.isEmpty(noticeList)){
                screenNotice.setSort(Long.valueOf(1));
            }else {
                screenNotice.setSort(noticeList.get(0).getSort()+1);
            }
            screenNotice.setDelFlag("0");
//            screenNotice.setCustomName(userInfoDetailVO.getCustomsName());
//            screenNotice.setCustomId(userInfoDetailVO.getCustomscode());
            screenNotice.setCreateTime(LocalDateTime.now());
            screenNotice.setSource("1");
            screenNotice.setYear(Long.valueOf(year));
            screenNotice.setUpdateBy(userInfoDetailVO.getUserId());
            screenNotice.setCustomId(userInfoDetailVO.getCustomscode());
            screenNotice.setApplyTime(LocalDateTime.now());
            screenNotice.setUpdateTime(LocalDateTime.now());
            screenNotice.setStatus("0");
            screenNoticeRepository.save(screenNotice);
            List<FileVO> files = screenNoticeSaveVO.getFiles();
            files.forEach(fileVO -> {
                LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Appendix::getId,fileVO.getId()).set(Appendix::getRelevanceId,screenNotice.getId());
                appendixRepository.update(wrapper);
            });
        }else {
            BeanUtils.copyProperties(screenNoticeSaveVO,screenNotice);
            if(StringUtils.isEmpty(screenNoticeSaveVO.getMainBody())){
                screenNotice.setMainBody("");
            }
            ScreenNotice byId = screenNoticeRepository.getById(screenNoticeSaveVO.getId());
            if(byId!=null){
                screenNotice.setRecVersion(byId.getRecVersion());
            }
            screenNotice.setUpdateTime(LocalDateTime.now());
            screenNotice.setUpdateBy(userInfoDetailVO.getUserId());
            screenNoticeRepository.updateById(screenNotice);
            List<FileVO> files = screenNoticeSaveVO.getFiles();
            List<Appendix> list = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,screenNotice.getId()));
            if (CollectionUtils.isEmpty(list)) {
                if (!CollectionUtils.isEmpty(files)) {
                    files.forEach(s -> {
                        LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.eq(Appendix::getId,s.getId()).set(Appendix::getRelevanceId,screenNotice.getId());
                        appendixRepository.update(wrapper);
                    });
                }
            }else {
                if (CollectionUtils.isEmpty(files)) {
                    if (!CollectionUtils.isEmpty(list)) {
                        appendixRepository.remove(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, screenNotice.getId()));
                    }
                }else {
                    List<String> collect = files.stream().map(FileVO::getId).collect(Collectors.toList());
                    List<String> collect3 = list.stream().map(Appendix::getId).collect(Collectors.toList());
                    List<String> collect1 = collect3.stream().filter(item -> !collect.contains(item)).collect(Collectors.toList());
                    appendixRepository.removeByIds(collect1);
                    List<String> collect2 = collect.stream().filter(item-> !collect3.contains(item)).collect(Collectors.toList());
                    collect2.forEach(s -> {
                        LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.eq(Appendix::getId,s).set(Appendix::getRelevanceId,screenNotice.getId());
                        appendixRepository.update(wrapper);
                    });
                }
            }
        }
      return BaseResult.ok(screenNotice,"保存成功");
    }

    @Override
    public BaseResult<ScreenNoticeSaveVO> detail(String id) {
        ScreenNotice byId = screenNoticeRepository.getById(id);
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
        ScreenNoticeSaveVO screenNoticeSaveVO = new ScreenNoticeSaveVO();
        BeanUtils.copyProperties(byId,screenNoticeSaveVO);
        screenNoticeSaveVO.setFiles(fileVOS);
        return BaseResult.ok(screenNoticeSaveVO,"查看成功");
    }

//    @Override
////    @Transactional(rollbackFor = Exception.class)
//    public BaseResult publish(List<String> ids, UserInfoDetailVO userInfoDetailVO) {
//        ScreenNotice notice = new ScreenNotice();
//        for (String id : ids) {
//            ScreenNotice byId = screenNoticeRepository.getById(id);
//            List<ScreenNotice> noticeList=screenNoticeRepository.list(new LambdaQueryWrapper<ScreenNotice>()
//                    .eq(ScreenNotice::getYear,byId.getYear()).eq(ScreenNotice::getStatus,"1").orderByDesc(ScreenNotice::getSort));
//            BeanUtils.copyProperties(byId,notice);
//            if(!CollectionUtils.isEmpty(noticeList)){
//                if(noticeList.get(0).getSort()!=null){
//                    notice.setSort(noticeList.get(0).getSort()+1);//序号
//                }else {
//                    notice.setSort(Long.valueOf(1));//序号
//                }
//            }else {
//                notice.setSort(Long.valueOf(1));//序号
//            }
//            notice.setStatus("1");
//            if("1".equals(byId.getSource())){
//                notice.setApplyTime(LocalDateTime.now());
//            }
//            notice.setUpdateBy(userInfoDetailVO.getUserId());
//            notice.setUpdateTime(LocalDateTime.now());
//            screenNoticeRepository.updateById(notice);
//        }
//        return BaseResult.ok(null,"批量发布成功");
//    }

    @Override
    public BaseResult<postarticlesVO> postarticles(String id) {
        ScreenNotice screenNotice = screenNoticeRepository.getById(id);
        String sort=null;
        if(screenNotice.getSort()!=null){
            if(screenNotice.getSort()>=1&&screenNotice.getSort()<10){
                sort="00"+screenNotice.getSort()+"号";
            }else if(screenNotice.getSort()>=10   &&screenNotice.getSort()<100){
                sort="0"+screenNotice.getSort()+"号";
            }else {
                sort=screenNotice.getSort()+"号";
            }
        }
        String postarticles="杭关办公告"+"〔"+screenNotice.getYear()+"〕"+sort;
        postarticlesVO postarticlesVO = new postarticlesVO();
        postarticlesVO.setTitle(screenNotice.getTitle());
        postarticlesVO.setCreatePerson(screenNotice.getCreatePerson());
        postarticlesVO.setMainBody(screenNotice.getMainBody());
        postarticlesVO.setPostarticles(postarticles);
        return BaseResult.ok(postarticlesVO,"成功");
    }

    @Override
    public Object hide(ScreenMessageDistributeHideDTO screenMessageDistributeHideDTO) {
        ScreenNotice screenDutyExperience=repository.getById(screenMessageDistributeHideDTO.getId());
        screenDutyExperience.setStatus(screenMessageDistributeHideDTO.getStatus());
        return repository.updateById(screenDutyExperience);
    }


}
